<?php
class ArticleModel extends ViewModel{
	//文章操作表
	public $table = 'article';
	//自动完成（给字段赋值）
	public $auto=array(
		array('addtime','time','function',2,1),
		array('updatetime','time','function',2,1),
		//获得文章的发布者管理员ID
		array('admin_id','get_adminid','method',2,3),
		//获得文章的发布者管理员ID
		array('author','get_author','method',2,3)
	);
	public $view=array(
		'article' =>array(
			'_type'=>'LEFT'
			),
		'category'=>array(
			'_on'=>'article.catid=category.cid'
		)
	);
	public function get_adminid(){
		return session('uid');
	}
	public function get_author(){
		return empty($_POST['author'])?session('username'):$_POST['author'];
	}
	public function add_article(){
		if($this->create()){
			if(!empty($_FILES['thumb']['name'])){
				$upload = new Upload('Uploads/image/'.date("Y/m"));
				$file = $upload->upload();
				$this->data['thumb']=$file[0]['path'];
			}
			return $this->add();
		}
	}
	public function edit_article(){
		if($this->create()){
			if(!empty($_FILES['thumb']['name'])){
				$upload = new Upload('Uploads/image/'.date("Y/m"));
				$file = $upload->upload();
				$this->data['thumb']=$file[0]['path'];
				//删除旧的缩略图
				$thumb= $this->where("id=".Q("id"))->getField('thumb');
				is_file($thumb)and unlink($thumb);
			}
			return $this->save();
		}
	}
	public function del_article(){
		$id=Q("id");
		if(empty($id)){
			return false;
		}else{
			if( is_array($id)){
				foreach($id as $id){
					$thumb= $this->where("id=".$id)->getField('thumb');
					is_file($thumb)and unlink($thumb);
					$this->del($id);
				}
				return true;
			}else{
				$thumb= $this->where("id=".$id)->getField('thumb');
				is_file($thumb)and unlink($thumb);
				$this->del($id);
				return true;
			}
		}
	}
}